<?php
/**
 * Created by PhpStorm.
 * User: PC
 * Date: 2018/6/29
 * Time: 16:17
 */
namespace common\helpers;


use yii\db\Query;

class Tools
{
    /**
     * 生成操作按钮
     * @param array $operate
     * @return string
     */
    public static function showOperate($operate = [])
    {
        if(empty($operate)){
            return '';
        }

        $option = '';
        foreach($operate as $key => $vo){
            if(self::authCheck($vo['auth']) || (1 == \Yii::$app->session->get('admin_id'))){
                $option .= ' <a href="' . $vo['href'] . '"><button type="button" class="btn btn-' . $vo['btnStyle'] . ' btn-sm">'.
                    '<i class="' . $vo['icon'] . '"></i> ' . $key . '</button></a>';
            }
        }

        return $option;
    }

    /**
     * 权限检测
     * @param $rule
     * @return bool
     */
    public static function authCheck($rule)
    {
        $cache = \Yii::$app->cache;
        $session = \Yii::$app->session;

        // 超级管理员跳过权限
        if(1 == $session->get('admin_id')){
            return true;
        }

        $key = 'role_' . $session->get('role_id') . '_auth';
        $authRule = empty($cache->get($key)) ? [] : unserialize($cache->get($key));

        // 可跳过的权限节点
        $skipRule = [
            'site/index',
            'site/first'
        ];

        if(in_array($rule, array_merge($authRule, $skipRule))){
            return true;
        }

        return false;
    }

    /**
     * json压缩
     * @param $data
     * @return string
     */
    public static function json($data)
    {
        return json_encode($data);
    }

    /**
     * 根据就是生成菜单
     * @param $roleId
     * @return array
     */
    public static function makeMenu($roleId)
    {
        if(1 == $roleId){

            // 超级管理员是整个菜单
            $menu = (new Query())->from('rbac_nodes')->where(['is_menu' => 2])->all();
        }else {

            $menu = unserialize(\Yii::$app->cache->get('role_' . $roleId . '_menu'));
        }

        return self::getTree($menu);
    }

    /**
     * 整理出tree数据
     * @param $pInfo
     * @param $spread
     */
    public static function getTree($pInfo)
    {
        $res = [];
        $tree = [];

        // 整理数组
        foreach($pInfo as $key => $vo){

            $res[$vo['node_id']] = $vo;
            $res[$vo['node_id']]['children'] = [];
        }
        unset($pInfo);

        // 查找子孙
        foreach($res as $key => $vo){
            if(0 != $vo['parent_node_id']){
                $res[$vo['parent_node_id']]['children'][] = &$res[$key];
            }
        }

        // 过滤杂质
        foreach( $res as $key => $vo ){
            if(0 == $vo['parent_node_id']){
                $tree[] = $vo;
            }
        }
        unset( $res );

        return $tree;
    }
}